//
//  SYComposeVC.swift
//  SYWeibo
//
//  Created by Saya on 16/4/15.
//  Copyright © 2016年 黄金果. All rights reserved.
//

import UIKit
import SVProgressHUD

class SYComposeVC: UIViewController {
    
    private lazy var picturePickVC:SYPicturePickVC = SYPicturePickVC()
    
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func selectPicture(){
        //需要将picturePick的controller给创建出来,在将他添加到当前控制器中,并且将视图也添加上去,但是为什么要添加控制器呢?
        addChildViewController(picturePickVC)
        view.addSubview(picturePickVC.view)
        picturePickVC.view.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentTextView.snp_bottom)
            make.left.right.equalTo(self.view)
            make.height.equalTo(self.view.frame.size.height / 3 * 2)
        }
        view.bringSubviewToFront(myToolBar)
     }
    
    @objc private func selectEmoticon(){
        
    }
    
    @objc private func sendBtnDidClick(){
        guard let access :String = SYVIewModel.viewModel.userInformation?.access_token else{
            SVProgressHUD.showErrorWithStatus("用户没有登录!!--no access")
            return
        }
        
        SYAFNTools.shareTools.sendWeibo(access, status: contentTextView.text, images: picturePickVC.imageList) { (reslut, error) -> Void in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("用户没有登录")
                return
            }
            self.close()
            SVProgressHUD.showSuccessWithStatus("发表日志成功")
        }
    }
    
    @objc private func keyboardChange(info:NSNotification){
        let endFrame:CGRect = info.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        let offset:CGFloat =  -screenHeight + endFrame.origin.y
        myToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        view.endEditing(true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setUpUI()
//        contentTextView.becomeFirstResponder()
        navigationItem.rightBarButtonItem?.enabled = false
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    private func setUpUI(){
        setNavBar()
        setTextView()
        setToolbar()
    }
    
    private func setNavBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = rightBtn
        navigationItem.titleView = titleview
    }
    
    private func setTextView(){
        view.addSubview(contentTextView)
        contentTextView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(self.view.frame.size.height / 3)
        }
        
        contentTextView.addSubview(placeHoldLB)
        placeHoldLB.snp_makeConstraints(closure: { (make) -> Void in
            make.top.equalTo(contentTextView.snp_top).offset(8)
            make.left.equalTo(contentTextView.snp_left).offset(5)
        })
    }
    
    private func setToolbar(){
        view.addSubview(myToolBar)
        myToolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.right.equalTo(view)
        }
    }
    
    private lazy var myToolBar:UIToolbar = {
        let toolbar = UIToolbar()
        let toolArray:[[String:String]] =  [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        let flexItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
        toolbar.items = [UIBarButtonItem]()
        
        for toolModel in toolArray {
            let tempBarItem = UIBarButtonItem(image: UIImage(named: toolModel["imageName"]!), style: UIBarButtonItemStyle.Plain, target: self, action: Selector(toolModel["actionName"]!))
            toolbar.items?.append(tempBarItem)
            toolbar.items?.append(flexItem)
        }
        toolbar.items?.removeLast()
//        toolbar.barStyle = .Default
        return toolbar
    }()
    
    private lazy var contentTextView:UITextView = {
        let tempTextView = UITextView()
        tempTextView.delegate = self
        tempTextView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        let redview = UIView()
        redview.backgroundColor = UIColor.redColor()
        tempTextView.inputAccessoryView = redview
        return tempTextView
    }()
    
    private lazy var placeHoldLB:UILabel = UILabel(text: "T听说下雨天巧克力和辣条更陪哦", font: 13, textColor: UIColor.lightGrayColor(), margin: marginForCell)
    
    private lazy var rightBtn:UIBarButtonItem = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        btn.setTitle("发送", forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Highlighted)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        
        btn.addTarget(self, action: "sendBtnDidClick", forControlEvents: .TouchUpInside)
        return UIBarButtonItem(customView: btn)
    }()
    
    private lazy var titleview:UIView = {
        let titleView = UIView()
        titleView.bounds = CGRect(x: 0, y: 0, width: 200, height: 40)
//        titleView.backgroundColor = UIColor.redColor()
        let nameLB = UILabel(text: "新浪微博", font: 14, textColor: UIColor.darkGrayColor())
        
        let subTitle = UILabel(text: (SYVIewModel.viewModel.userInformation?.name)!, font: 12, textColor: UIColor.lightGrayColor())
        
        //添加并且设置frame
        titleView.addSubview(nameLB)
        titleView.addSubview(subTitle)
        let width:CGFloat = titleView.frame.size.width
        let height:CGFloat = titleView.frame.size.height
        nameLB.frame = CGRect(x: 0, y: 0, width: width, height: height * 2 / 3)
        subTitle.frame = CGRect(x: 0, y: height * 2 / 3, width: width, height: height / 3)
        
        return titleView
    }()
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}


extension SYComposeVC:UITextViewDelegate{
    @objc func textViewDidChange(textView: UITextView) {
        placeHoldLB.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}






























